package com.shoufeng.demo.server;

import com.shoufeng.demo.service.HealthServiceImpl;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class HealthServer {

  private static final String USER_DIR_PATH = System.getProperty("user.dir");

  private Server server;

  @Autowired
  private HealthServiceImpl healthService;

  public void start() throws IOException {
    this.server = ServerBuilder.forPort(8090).addService(healthService).build().start();
    System.out.println("server start!");
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
      System.out.println("关闭jvm");
      HealthServer.this.stop();
    }));
//    System.out.println("执行到这里");
  }

  private void stop() {
    if (null != this.server) {
      this.server.shutdown();
    }
  }

  public void awaitTermination() throws InterruptedException {
    if (null != this.server) {
//      this.server.awaitTermination(3000, TimeUnit.MILLISECONDS);
      this.server.awaitTermination();
    }
  }
}
